package com.JobFind.DAO.impl;

import java.util.List;

import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.JobFind.DAO.IUserDAO;
import com.JobFind.model.TbUser;

@Component
public class UserDAO implements IUserDAO {
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public List<TbUser> loginCheck(String userLoginName) throws Exception {
		List<TbUser> result = null;
		Session session = sessionFactory.getCurrentSession();
		String hql = "from TbUser where userLoginName = ?";
		Query query = session.createQuery(hql);
		query.setString(0,userLoginName);
		result = query.list();
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<TbUser> getUserInfoById(Integer userId) throws Exception{
		List<TbUser> result = null;
		Session session = sessionFactory.getCurrentSession();
		String hql = "from TbUser where userId = ?";
		Query query = session.createQuery(hql);
		query.setInteger(0,userId);
		result = query.list();
		return result;
	}


	public Integer updateUserInfo(Integer userId,String homePlace, String birthday,
			String userNickName, String userNation) throws Exception {
		Integer result = 1;
		try {
			Session session = sessionFactory.getCurrentSession();
			String hql = "update TbUser set homePlace=?,userBirthday=?,userNickName=?,userNation=? where userId=?";
			Query query = session.createQuery(hql);
			query.setString(0, homePlace);
			query.setString(1, birthday);
			query.setString(2, userNickName);
			query.setString(3, userNation);
			query.setInteger(4, userId);
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			result = 0;
		}
		return result;
	}

	public Integer modifyUserPwd(Integer userId, String userPwd)
			throws Exception {
		Integer result = 1;
		try {
			Session session = sessionFactory.getCurrentSession();
			String hql = "update TbUser set userPwd=? where userId=?";
			Query query = session.createQuery(hql);
			query.setString(0, userPwd);
			query.setInteger(1, userId);
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			result = 0;
		}
		return result;
	}

	public Integer addUser(TbUser userBean) throws Exception {
		Integer result = 0;
		try {
			Session session = sessionFactory.getCurrentSession();
			result = (Integer) session.save(userBean);
		} catch (Exception e) {
			e.printStackTrace();
			result = 0;
		}
		return result;
	}
}
